//
//  CategoryBtu.swift
//  FM
//
//  Created by x on 2017/8/24.
//  Copyright © 2017年 HLB. All rights reserved.
//

import UIKit

class CategoryBtu: UIButton {

    /// 设置按钮的点击区域
    ///
    /// - Parameters:
    ///   - point: <#point description#>
    ///   - event: <#event description#>
    /// - Returns: <#return value description#>
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let rect = CGRect.init(x: 10, y: 0, width: bounds.width-20, height: bounds.height)
        if rect.contains(point) {
            return super.hitTest(point, with: event)
        }else {
            return nil
        }
    }
    
    /// 快速创建一个自定义按钮
    ///
    /// - Parameters:
    ///   - imageUrl: <#imageUrl description#>
    ///   - frame: <#frame description#>
    ///   - title: <#title description#>
    ///   - tag: <#tag description#>
    ///   - target: <#target description#>
    ///   - action: <#action description#>
    /// - Returns: <#return value description#>
    class func creatButton(imageUrl:URL, frame:CGRect, title:String, tag:Int, target:Any?, action:Selector) -> CategoryBtu {
        
        let btn = CategoryBtu()
        btn.frame = frame
        //设置图片
        SDWebImageManager.shared().loadImage(with: imageUrl, options: SDWebImageOptions.init(rawValue: 0), progress: nil) { (image, _, error, _, finish, url) in
            guard error != nil else {
                btn.setImage(image, for: UIControlState.normal)
                return
            }
        }
//        SDWebImageManager.shared().downloadImage(with: imageUrl, options: SDWebImageOptions.init(rawValue: 0), progress: nil, completed: { (image, error, _, finish, url) in
//            guard error != nil else {
//                btn.setImage(image, for: UIControlState.normal)
//                return
//            }
//        })
        btn.setTitle(title, for: UIControlState.normal)
        btn.setTitleColor(UIColor.black, for: UIControlState.normal)
        btn.tag = tag
        btn.addTarget(target, action: action, for: UIControlEvents.touchUpInside)
        
        return btn
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        titleLabel?.textAlignment = NSTextAlignment.center
        titleLabel?.font = UIFont.systemFont(ofSize: 13)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        imageView?.frame = CGRect.init(x: bounds.width/2-15, y: 5, width: 30, height: 30)
        titleLabel?.frame = CGRect.init(x: 0, y: bounds.height-20, width: bounds.width, height: 20)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
